package com.lsd.game.lastrun.view;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Rectangle;
import com.lsd.game.lastrun.Constants;
import com.lsd.game.lastrun.model.AbstractObject;
import com.lsd.game.lastrun.model.World;

public class WorldRenderer {
	
	private World world;
	private OrthographicCamera cam;
	
	// Debug rendering //
	ShapeRenderer debugRenderer = new ShapeRenderer();
	private boolean debug = false;
	
	private SpriteBatch spriteBatch;
	private int height;
	private int width;
	private float ppuX; // Pixels per unit on the X axis
	private float ppuY; // Pixels per unit on the Y axis
	public void setSize(int w, int h) {
		this.width = w;
		this.height = h;
		ppuX = (float)width / Constants.CAMERA_WIDTH;
		ppuY = (float)height / Constants.CAMERA_HEIGHT;
	}
	
	public WorldRenderer(World world, boolean debug) {
		this.world = world;
		this.cam = new OrthographicCamera(Constants.CAMERA_WIDTH, Constants.CAMERA_HEIGHT);
		this.cam.position.set(Constants.CAMERA_WIDTH / 2, Constants.CAMERA_HEIGHT / 2, 0);
		this.cam.update();
		this.debug = debug;
		spriteBatch = new SpriteBatch();
	}
	
	public void render() {
		spriteBatch.begin();
			// drawRocks();
			// drawPlayer();
			drawObject();
		spriteBatch.end();
		if (debug)
			drawDebug();
	}

	private void drawObject() {
		for (AbstractObject obj: world.getObjects())
		spriteBatch.draw(obj.getTexture(), obj.getPosition().x * ppuX,  obj.getPosition().y * ppuY, obj.getSize() * ppuX, obj.getSize() * ppuY);
	}
	
	public void drawDebug() {
		debugRenderer.setProjectionMatrix(cam.combined);
		debugRenderer.begin(ShapeType.Line);
		
		for (AbstractObject obj: world.getObjects()) {
			// TODO: Set colors for different types of objects
			Rectangle rect = obj.getDebugRect();
			float x1 = obj.getPosition().x + rect.x;
			float y1 = obj.getPosition().y + rect.y;
			if (obj.getClass().getSimpleName().equals("Rock"))
				debugRenderer.setColor(new Color(1, 1, 0, 1));
			else
				debugRenderer.setColor(new Color(1, 0, 0, 1));
			debugRenderer.rect(x1, y1, rect.width, rect.height);
		}
		
		debugRenderer.end();
	}
}
